package com.culture.config.core;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import lombok.extern.slf4j.Slf4j;

import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

@Slf4j
@Configuration
@EnableAsync
public class ExecutorConfiguration implements AsyncConfigurer, AsyncUncaughtExceptionHandler { 
    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();
    
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return this;
	}

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(PROCESSORS);
        executor.setMaxPoolSize(PROCESSORS*2);
        executor.setQueueCapacity(100);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.setThreadNamePrefix("thread-configure-");
        executor.initialize();
        return executor;
	}

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
       log.error("Async thread error:", ex);        
       log.error("Async thread error method:{}", method); 
       log.error("Async thread error params:{}", params); 
    }
   
}
